#!/usr/bin/env python
# -*- coding: utf-8 -*-
#===============================================================================
# Copyright 2011 zod.yslin
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# 
# Author: zod.yslin
# Email: 
# File Name: mmap_.py
# Description: 
#   Add _ to avoid conflict with standard library.
# Edit History: 
#   2011-11-01    File created.
#===============================================================================
import mmap

# write a simple example file
with open("hello.txt", "wb") as f:
    f.write("Hello Python!\n")

with open("hello.txt", "r+b") as f:
    # memory-map the file, size 0 means whole file
    memap = mmap.mmap(f.fileno(), 0, mmap.MAP_PRIVATE)
    # read content via standard file methods
    print(memap.readline())  # prints "Hello Python!"
    # read content via slice notation
    print(memap[:5])  # prints "Hello"
    # update content using slice notation;
    # note that new content must have same size
    memap[6:] = " world!\n"
    # ... and read again using standard file methods
    memap.seek(0)
    print(memap.readline())  # prints "Hello  world!"
    # close the map
    memap.close()

# create an anonymous map and exchange data between the parent and child processes
import mmap
import os

map = mmap.mmap(-1, 13)
map.write("Hello world!")

pid = os.fork()

if pid == 0: # In a child process
    map.seek(0)
    print '[child]', map.readline()

    map.close()
